<template>
  <el-select clearable style="width:100%" v-model="model" :collapse-tags="collapseTags" :multiple="multiple"
    suffix-icon="" v-loading="loading" @click.capture="handleClick"
    @input="v => $emit('input', v)" placeholder="点击选择">
    <el-option v-for="option in options" :key="option[idKey]" :label="option[labelKey]"
      :value="option[idKey]"></el-option>
  </el-select>
</template>
<script setup>
import { watch } from 'vue';
const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  },
  clearable: {
    type: Boolean,
    default: false
  },
  collapseTags: {
    type: Boolean,
    default: false
  },
  options: {
    type: Array,
    default: () => []
  },
  idKey: {
    type: String,
    default: "id"
  },
  labelKey: {
    type: String,
    default: "name"
  }
})

const model = defineModel()
const emits = defineEmits(["click"])
const handleClick = (e) => {
  console.log(e)
  if (typeof e.target.className == "string") {
    e.stopPropagation();
    emits("click");
  }
}
watch(model, (v) => {
  for (let i = 0; i < props.options.length; i++) {
    if (props.multiple) {
      v = v || [];
      if (v.every(item => props.options[i][props.idKey] != item)) {
        props.options.splice(i, 1);
        i--;
      }
    } else {
      if (props.options[i][props.idKey] != v) {
        props.options.splice(i, 1);
        i--;
      }
    }
  }
})
</script>